package com.jy.admin.rest;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.MD5;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jy.admin.annotations.AdminSignIgnore;
import com.jy.admin.auth.anno.VisitorAccessible;
import com.jy.admin.auth.request.UnPushedListRequest;
import com.jy.admin.config.ApolloConfigUtil;
import com.jy.admin.db.dao.*;
import com.jy.admin.db.entity.*;
import com.jy.admin.enums.HighRupeeCollectionTagEnum;
import com.jy.admin.enums.OrderStatusEnum;
import com.jy.admin.enums.UnPushedListBean;
import com.jy.admin.jobs.BaseJobHandler;
import com.jy.admin.services.BaseCrawlerService;
import com.jy.admin.services.cashPocket.*;
import com.jy.bo.common.conf.api.ApiResponse;
import com.jy.bo.common.conf.util.HttpUtil;
import com.robert.vesta.util.IpUtils;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.jy.admin.services.cashPocket.SivanWalletService.execCurl;


@RestController
@RequestMapping("/order")
public class OrderController {
    private final static Logger LOGGER = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    RupeeGoService rupeeGoService;
    @Autowired
    private CeOrdersDao ordersDao;
    @Autowired
    private CeAgentAccountDao accountDao;
    @Autowired
    private CeMerchantDao merchantDao;

    @Autowired
    private LittleOrangeService littleOrangeService;

    @Autowired
    private ChenXingService chenXingService;

    @Autowired
    private ChenXingNewService chenXingNewService;


    @Autowired
    private InfinityCashService infinityCashService;

    @Autowired
    private FutureWalletService futureWalletService;

    @Autowired
    private LittleBorrowService littleBorrowService;

    @Autowired
    private CashPlannerService cashPlannerService;

    @Autowired
    private RupeeTigerService tigerService;
    @Autowired
    private OkRupeeService okRupeeService;

    @Autowired
    private DosService dosService;

    @Autowired
    private CeCommentPushLogDao commentPushLogDao;

    @Autowired
    private ApolloConfigUtil configUtil;

    @Autowired
    private CeAgentAccountDao agentAccountDao;

    @Autowired
    private CashBroService cashBroService;

    @Autowired
    private PrettyLoanService prettyLoanService;

    @Autowired
    private CeRepaymentLinkDao repaymentLinkDao;

    @AdminSignIgnore
    @RequestMapping("/repay/link")
    public ApiResponse getRepaymentLink(String collectionNo, boolean isReduce) {
        String repaymentLink = "";
        if (StringUtils.isNotEmpty(collectionNo)) {
            try {
                CeOrdersEntity oneByCollectionNo = ordersDao.getOneByCollectionNo(collectionNo);
                if (oneByCollectionNo != null) {
                    if (BaseJobHandler.merchantAndServiceMap.containsKey(oneByCollectionNo.getMerchantCode())) {
                        LOGGER.info("== getRepaymentLink==，merchant:{},orderNo:{}", oneByCollectionNo.getMerchantCode(), oneByCollectionNo.getOrderNo());
                        repaymentLink = BaseJobHandler.merchantAndServiceMap.get(oneByCollectionNo.getMerchantCode()).updateRepaymentLink(collectionNo, isReduce);
                        LOGGER.info("== getRepaymentLink==，repaymentLink:{}", repaymentLink);
                    }
                }

            } catch (Exception e) {
                repaymentLink = "create link failed";
            }
        }
        return new ApiResponse(repaymentLink);
    }

    @AdminSignIgnore
    @RequestMapping("/unification/repay/link")
    public ApiResponse getNewRepaymentLink(String collectionNo, boolean isReduce) {
        String repaymentLink = "";
        if (StringUtils.isNotEmpty(collectionNo)) {
            try {
                CeRepaymentLinkEntity oneByCollectionNo = repaymentLinkDao.getOneByCollectionNo(collectionNo, 0);
                if (System.currentTimeMillis() - oneByCollectionNo.getGmtCreate().getTime() > 5 * 60 * 1000) {//5分钟
                    repaymentLink = "The link is invalid, please contact customer service to obtain again";
                } else {
                    repaymentLink = oneByCollectionNo.getPaymentUrl();
                }
            } catch (Exception e) {
                repaymentLink = "create link failed";
            }
        }
        return new ApiResponse(repaymentLink);
    }

    @AdminSignIgnore
    @RequestMapping("/extention/repay/link")
    public ApiResponse getExtensionRepaymentLink(String collectionNo, boolean isOpen) {
        String repaymentLink = "";
        if (StringUtils.isNotEmpty(collectionNo)) {
            try {
                CeOrdersEntity oneByCollectionNo = ordersDao.getOneByCollectionNo(collectionNo);
                if (oneByCollectionNo != null) {
                    if (BaseJobHandler.merchantAndServiceMap.containsKey(oneByCollectionNo.getMerchantCode())) {
                        LOGGER.error("== getExtensionRepaymentLink==，merchant:{},orderNo:{}", oneByCollectionNo.getMerchantCode(), oneByCollectionNo.getOrderNo());
                        repaymentLink = BaseJobHandler.merchantAndServiceMap.get(oneByCollectionNo.getMerchantCode()).updateExtensionRepaymentLink(collectionNo, isOpen);
                        LOGGER.error("== getExtensionRepaymentLink==，repaymentLink:{}", repaymentLink);
                    }
                }

            } catch (Exception e) {
                repaymentLink = "create extension link failed";
            }
        }
        return new ApiResponse(repaymentLink);
    }

    @AdminSignIgnore
    @RequestMapping("/add/payment")
    public ApiResponse addPaymentOrder(String orderNo, String fileUrl, String utr, String remark, String amount) {
        String msg = "";
        if (StringUtils.isNotEmpty(orderNo)) {
            try {
                CeOrdersEntity oneByCollectionNo = ordersDao.getTodayOneByOrderNo(orderNo);
                if (oneByCollectionNo != null) {
                    if (BaseJobHandler.merchantAndServiceMap.containsKey(oneByCollectionNo.getMerchantCode())) {
                        LOGGER.error("== addPaymentOrder==，merchant:{},orderNo:{}", oneByCollectionNo.getMerchantCode(), oneByCollectionNo.getOrderNo());
                        String result = BaseJobHandler.merchantAndServiceMap.get(oneByCollectionNo.getMerchantCode()).addPaymentOrder(orderNo, "", fileUrl, utr, remark, amount);
                        LOGGER.error("== addPaymentOrder==，result:{}", result);
                        msg = result;
                    }
                }

            } catch (Exception e) {
                msg = "Add Replenishment Order Failed!";
            }
        }
        return new ApiResponse(msg);
    }

    @AdminSignIgnore
    @RequestMapping("/query/payment")
    public ApiResponse queryPaymentOrder(String orderNo, String utr) {
        String msg = "";
        if (StringUtils.isNotEmpty(orderNo)) {
            try {
                CeOrdersEntity oneByCollectionNo = ordersDao.getTodayOneByOrderNo(orderNo);
                if (oneByCollectionNo != null) {
                    if (BaseJobHandler.merchantAndServiceMap.containsKey(oneByCollectionNo.getMerchantCode())) {
                        LOGGER.error("== queryPaymentOrder==，merchant:{},orderNo:{}", oneByCollectionNo.getMerchantCode(), oneByCollectionNo.getOrderNo());
                        String result = BaseJobHandler.merchantAndServiceMap.get(oneByCollectionNo.getMerchantCode()).queryPaymentOrderResult(orderNo, utr);
                        LOGGER.error("== queryPaymentOrder==，result:{}", result);
                        msg = result;
                    }
                }

            } catch (Exception e) {
                msg = "Query Failed!";
            }
        }
        return new ApiResponse(msg);
    }


    @AdminSignIgnore
    @RequestMapping("/update/list")
    public ApiResponse getUpdateList(String agentCode) {
        String msg = "";
        try {
            CeAgentAccountEntity byAgentCode = accountDao.getByAgentCode(agentCode);
            if (byAgentCode != null) {
                if (BaseJobHandler.merchantAndServiceMap.containsKey(byAgentCode.getMerchantCode())) {
                    BaseJobHandler.merchantAndServiceMap.get(byAgentCode.getMerchantCode()).updateOrderList(byAgentCode);
                }
            } else {
                msg = "query failed";
            }

        } catch (Exception e) {
            msg = "query failed";
        }
        return new ApiResponse(msg);
    }


    @AdminSignIgnore
    @RequestMapping("/login")
    @VisitorAccessible
    public String oklogin(String agentCode, String code) {
        CeAgentAccountEntity byAgentCode = accountDao.getByAgentCode(agentCode);
        String login = littleOrangeService.login(byAgentCode, code);
        return login;
    }

    @AdminSignIgnore
    @RequestMapping("/chenxing/captchakey")
    @VisitorAccessible
    public String oklogin() {
        String captchaContent = chenXingService.getCaptchakey();
        return captchaContent;
    }

    @AdminSignIgnore
    @RequestMapping("/chenxing/captchakeybase")
    @VisitorAccessible
    public String captchakeyBase() {
        String captchaContent = chenXingService.getCaptchakeyBase();
        return captchaContent;
    }

    @AdminSignIgnore
    @RequestMapping("/chenxing/login")
    @VisitorAccessible
    public String chenxingLogin(String agentCode, String code) {
        CeAgentAccountEntity byAgentCode = accountDao.getByAgentCode(agentCode);
        String login = chenXingService.login(byAgentCode, code);
        return login;
    }
    @AdminSignIgnore
    @RequestMapping("/chenxingnew/captchakeybase")
    @VisitorAccessible
    public String captchakeyNewBase() {
        String captchaContent = chenXingNewService.getCaptchakeyBase();
        return captchaContent;
    }

    @AdminSignIgnore
    @RequestMapping("/chenxingnew/login")
    @VisitorAccessible
    public String chenxingNewLogin(String agentCode, String code) {
        CeAgentAccountEntity byAgentCode = accountDao.getByAgentCode(agentCode);
        String login = chenXingNewService.login(byAgentCode, code);
        return login;
    }

    @AdminSignIgnore
    @RequestMapping("/papamoney/login")
    @VisitorAccessible
    public String papamoneyLogin(String agentCode, String code, String key) {
        CeAgentAccountEntity byAgentCode = accountDao.getByAgentCode(agentCode);
        String login = infinityCashService.login(byAgentCode, code, key);
        return login;
    }

    @AdminSignIgnore
    @RequestMapping("/futurewallet/login")
    @VisitorAccessible
    public String futurewalletLogin(String agentCode, String code, String key) {
        CeAgentAccountEntity byAgentCode = accountDao.getByAgentCode(agentCode);
        String login = futureWalletService.login(byAgentCode, code, key);
        return login;
    }

    @RequestMapping(value = "/littleborrow/captchakey", produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] borrowKey(String merchantCode) {
        byte[] captchaContent = littleBorrowService.getCaptchakey(merchantCode);
        return captchaContent;
    }

    @AdminSignIgnore
    @RequestMapping("/littleborrow/login")
    @VisitorAccessible
    public String borrowLogin(String agentCode, String code) {
        CeAgentAccountEntity byAgentCode = accountDao.getByAgentCode(agentCode);
        String login = littleBorrowService.login(byAgentCode, code);
        return login;
    }


    @AdminSignIgnore
    @RequestMapping("/send/note")
    @VisitorAccessible
    public String sendNote(String merchantCode) {
        try {
            List<CeOrdersEntity> notSendNoteOrder = ordersDao.getNotSendNoteOrder(merchantCode);
            LOGGER.info("== 没有催记的订单 ==,orderList:{}", JsonStream.serialize(notSendNoteOrder));
            int size = Math.min(notSendNoteOrder.size(), 50);
            for (int i = 0; i < size; i++) {
                CeCommentPushLogEntity entity = new CeCommentPushLogEntity();
                entity.setMerchantCode(merchantCode);
                entity.setAgentCode(notSendNoteOrder.get(i).getAgentCode());
                entity.setTargetType(110);
                entity.setTargetMsg("[Ringing No Response]");
                entity.setStatus(1);
                entity.setOriginNo(notSendNoteOrder.get(i).getOrderNo());
                JSONObject detail = new JSONObject();
                detail.put("mobile", "");
                detail.put("calling_result", null);
                detail.put("relation", "");
                detail.put("promise_pay_date", "");
                entity.setPushDetail(detail.toString());
                commentPushLogDao.insert(entity);
            }
            return "ok";
        } catch (Exception e) {
            return "err";
        }
    }


    @AdminSignIgnore
    @RequestMapping("/push")
    @VisitorAccessible
    public void pushDataToCollection() {
        Map<String, BaseCrawlerService> merchantAndServiceMap = BaseJobHandler.merchantAndServiceMap;
        String hostIp = IpUtils.getHostIp();
        if (!hostIp.equals(configUtil.getJobRunIp())) {
            LOGGER.info("==PayCallBackToBizJob==, 当前机器ip不是job执行机器,当前iP:{},目标IP:{}", hostIp, configUtil.getJobRunIp());
            return;
        }

        LOGGER.info("== pushDataToCollection 开始 pushDataToCollection==");
        List<CeMerchantEntity> allActiveMerchant = merchantDao.getAllActiveMerchant();

        allActiveMerchant.forEach(merchant -> {
            try {
                LOGGER.info("== pushDataToCollection 开始处理商户 ==,merchantCode:{}", merchant.getMerchantCode());

                if (!merchantAndServiceMap.containsKey(merchant.getMerchantCode())) {
                    LOGGER.error("== pushDataToCollection ==,找不到商户的处理逻辑，merchant:{}", merchant.getMerchantCode());
                    return;
                }

                List<CeAgentAccountEntity> accounts = accountDao.getAccountsMerchantCode(merchant.getMerchantCode());
                if (CollectionUtils.isEmpty(accounts)) {
                    LOGGER.info("== pushDataToCollection 商户下面没有账号 ==,merchantCode:{}", merchant.getMerchantCode());
                    return;
                }

                accounts.forEach(account -> {
                    try {

                        if (merchant.getStatus() == 2) {
                            LOGGER.info("== BaseJobHandler 开始处理商户,商户当前处于不可更新状态，status=2 ==,merchantCode:{}", merchant.getMerchantCode());
                            return;
                        }

                        LOGGER.info("== pushDataToCollection 开始处理账号 ==,account:{}", account.getAccount());
                        LOGGER.info("== pushDataToCollection 开始推送数据到催收 ==,account:{}", account.getAccount());

                        merchantAndServiceMap.get(account.getMerchantCode()).pushDataToCollection(account);

                        LOGGER.info("== pushDataToCollection 开始处理 当前账号处理完成==,，account:{}", account.getAccount());
                    } catch (Exception e) {
                        LOGGER.error("== pushDataToCollection 开始处理 异常==,，account:{}", account.getAccount(), e);
                    }
                });

                LOGGER.info("== pushDataToCollection 开始处理 当前商户处理完成==,，merchant:{}", merchant.getMerchantCode());

            } catch (Exception e) {
                LOGGER.error("pushDataToCollection 异常", e);
            }
        });
    }


    @AdminSignIgnore
    @RequestMapping("/check/paid")
    @VisitorAccessible
    public String checkOrderPaid(String orderNo) {
        try {
            CeOrdersEntity todayOneByOrderNo = ordersDao.getTodayOneByOrderNo(orderNo);
            if (todayOneByOrderNo != null) {
                if (BaseJobHandler.merchantAndServiceMap.containsKey(todayOneByOrderNo.getMerchantCode())) {
                    LOGGER.info("== getCheckOrder ==，merchant:{},orderNo:{}", todayOneByOrderNo.getMerchantCode(), todayOneByOrderNo.getOrderNo());
                    String result = BaseJobHandler.merchantAndServiceMap.get(todayOneByOrderNo.getMerchantCode()).checkOrdersPaid(orderNo);
                    LOGGER.info("== getCheckOrder ==，merchant:{},orderNo:{},result:{}", todayOneByOrderNo.getMerchantCode(), todayOneByOrderNo.getOrderNo(), result);
                    return result;
                }
            }

        } catch (Exception e) {
            LOGGER.info("== getCheckOrder ==,err:{}", e.getMessage());
        }

        return "";
    }


    @AdminSignIgnore
    @RequestMapping("/account/failure")
    @VisitorAccessible
    public ApiResponse getAllAccount() {
        List<CeAgentAccountEntity> accountsByStatus = accountDao.getAccountsByStatus(2);
        return new ApiResponse<>(accountsByStatus);
    }

    @AdminSignIgnore
    @RequestMapping("/account/login")
    @VisitorAccessible
    public ApiResponse getAccountLogin(String agentCode, String code) {
        CeAgentAccountEntity byAgentCode = accountDao.getByAgentCode(agentCode);
        String loginResult = "";
        if (byAgentCode.getMerchantCode().equals("littleorange")) {
            loginResult = littleOrangeService.login(byAgentCode, code);
        } else if (byAgentCode.getMerchantCode().equals("littleborrow") || byAgentCode.getMerchantCode().equals("cashg")) {
            loginResult = littleBorrowService.login(byAgentCode, code);
        } else if (byAgentCode.getMerchantCode().equals("papamoney")) {
            loginResult = infinityCashService.login(byAgentCode, code, "");
        }
        return new ApiResponse<>(loginResult);
    }

    @AdminSignIgnore
    @RequestMapping("/merchant/update")
    @VisitorAccessible
    public void updateDetails(String merchantCode) {
        if (BaseJobHandler.merchantAndServiceMap.containsKey(merchantCode)) {
            List<CeAgentAccountEntity> accountEntities = accountDao.getAccountsMerchantCode(merchantCode);
            accountEntities.forEach(agentAccountEntity -> {
                LOGGER.info("== updateDetails ==，agentAccount:{}", agentAccountEntity);
                BaseJobHandler.merchantAndServiceMap.get(merchantCode).updateOrderDetailInfo(agentAccountEntity);
            });
        }
    }

    @AdminSignIgnore
    @RequestMapping("/update/image")
    @VisitorAccessible
    public String updateDetailsImage(String orderNo) {
        try {
            CeOrdersEntity todayOneByOrderNo = ordersDao.getTodayOneByOrderNo(orderNo);
            CeMerchantEntity merchant = merchantDao.queryMerchantByCode(todayOneByOrderNo.getMerchantCode());
            CeAgentAccountEntity agentAccount = accountDao.getByAgentCode(todayOneByOrderNo.getAgentCode());
            LOGGER.info("== updateDetails ==，agentAccount:{}", agentAccount);
            Any orderInfo = JsonIterator.deserialize(todayOneByOrderNo.getOrderInfo());
            String loanNumber = orderInfo.get("loan_number").toString();
            String imageInfoUrl = merchant.getApiDomain() + "/api/loan_collection_case/" + loanNumber + "/client_face_recognition";
            Map<String, String> headers = getHeaders(agentAccount);
            String imageInfoResult = HttpUtil.getPageHttp(imageInfoUrl, headers);
            LOGGER.info("== 获取成功 baseInfo==");
            Any imageInfo = JsonIterator.deserialize(imageInfoResult).get("data");
            List<String> images = Lists.newArrayList();
            if (!imageInfo.get("head_img").toString().equals("")) {
                images.add(imageInfo.get("head_img").toString());
            }
            if (!imageInfo.get("id_card_pic").get("frontImg").toString().equals("")) {
                images.add(imageInfo.get("id_card_pic").get("frontImg").toString());
            }
            if (!imageInfo.get("id_card_pic").get("backImg").toString().equals("")) {
                images.add(imageInfo.get("id_card_pic").get("backImg").toString());
            }
            if (!imageInfo.get("pan_img").toString().equals("")) {
                images.add(imageInfo.get("pan_img").toString());
            }
            LOGGER.info("== 获取成功 images==");
            ordersDao.updateImages(todayOneByOrderNo.getOrderNo(), JsonStream.serialize(images), todayOneByOrderNo.getMerchantCode());
            return "update Success!";
        } catch (Exception e) {
            LOGGER.info("== 获取失败 images==,e:{},orderNo:{}", e, orderNo);
            return "update Fail!";
        }
    }

    @AdminSignIgnore
    @RequestMapping("/update/image/sivan")
    @VisitorAccessible
    public String updateDetailsImageSivanWallet(String orderNo) {
        try {
            CeOrdersEntity todayOneByOrderNo = ordersDao.getTodayOneByOrderNo(orderNo);
            CeMerchantEntity merchant = merchantDao.queryMerchantByCode(todayOneByOrderNo.getMerchantCode());
            CeAgentAccountEntity agentAccount = accountDao.getByAgentCode(todayOneByOrderNo.getAgentCode());
            LOGGER.info("== updateDetails ==，agentAccount:{}", agentAccount);
            Any orderInfo = JsonIterator.deserialize(todayOneByOrderNo.getOrderInfo());
            Map<String, String> headers = getHeaders(agentAccount);
            String id = orderInfo.get("id").toString();
            JSONObject param = new JSONObject();
            param.put("overdueId", id);
            String baseInfoUrl = "";
            if (agentAccount.getStage().equals("d-1") || agentAccount.getStage().equals("d0")) {
                baseInfoUrl = merchant.getApiDomain() + "/hs/admin/orderToday/detail";
            } else {
                baseInfoUrl = merchant.getApiDomain() + "/hs/admin/orderOverdue/detail";
            }
            String[] command2 = {"curl", "--location", "--request", "POST", baseInfoUrl, "--header", "Content-Type: application/json", "--header", "Cookie:" + headers.get("cookie"), "--data-raw", param.toString()};
            String baseInfoResult = execCurl(command2);
            Any baseInfo = JsonIterator.deserialize(baseInfoResult).get("data").get("userRealnameInfo");
            List<String> images = Lists.newArrayList();
            if (!baseInfo.get("idcardFrontPhoto").toString().equals("")) {
                String url = baseInfo.get("idcardFrontPhoto").toString();
                images.add(url);
            }
            if (!baseInfo.get("idcardBackPhoto").toString().equals("")) {
                String url = baseInfo.get("idcardBackPhoto").toString();
                images.add(url);
            }
            if (!baseInfo.get("panPhoto").toString().equals("")) {
                String url = baseInfo.get("panPhoto").toString();
                images.add(url);
            }
            if (!baseInfo.get("livingPhoto").toString().equals("")) {
                String url = baseInfo.get("livingPhoto").toString();
                images.add(url);
            }
            LOGGER.info("== 获取成功 images==");
            ordersDao.updateImages(todayOneByOrderNo.getOrderNo(), JsonStream.serialize(images), todayOneByOrderNo.getMerchantCode());
            return JsonStream.serialize(images);
        } catch (Exception e) {
            LOGGER.info("== 获取失败 images==,e:{},orderNo:{}", e, orderNo);
            return "update Fail!";
        }
    }

    public Map<String, String> getHeaders(CeAgentAccountEntity agentAccount) {
        String requestHeader = agentAccount.getRequestHeader();
        Map headers = Maps.newHashMap();
        if (com.fqgj.common.utils.StringUtils.isNotEmpty(requestHeader)) {
            Map<String, Any> stringAnyMap = JsonIterator.deserialize(requestHeader).asMap();
            stringAnyMap.keySet().forEach(k -> {
                headers.put(k, stringAnyMap.get(k).toString());
            });
        }

        return headers;
    }


    @AdminSignIgnore
    @RequestMapping("/tiger/login")
    @VisitorAccessible
    public String tigerLogin(String agentCode, String code, String googlecode) {
        String login = tigerService.login(agentCode, code);
        return login;
    }

    @AdminSignIgnore
    @RequestMapping("/okrupee/login")
    @VisitorAccessible
    public String okrupeeLogin(String agentCode, String cookie) {
        String login = okRupeeService.manualLogin(agentCode, cookie);
        return login;
    }

    @AdminSignIgnore
    @RequestMapping("/dos/login")
    @VisitorAccessible
    public String dosLogin(String agentCode, String code) {
        String login = dosService.login(agentCode, code);
        return login;
    }

    @AdminSignIgnore
    @RequestMapping("/kinwings/login")
    @VisitorAccessible
    public String kinwingslogin(String agentCode, String code) {
        CeAgentAccountEntity byAgentCode = accountDao.getByAgentCode(agentCode);
        String login = cashPlannerService.login(byAgentCode, code);
        return login;
    }

    @RequestMapping(value = "/kinwings/code", produces = MediaType.IMAGE_JPEG_VALUE)
    @ResponseBody
    public byte[] kinwingslogin(String agentCode) {
        CeAgentAccountEntity byAgentCode = accountDao.getByAgentCode(agentCode);
        byte[] code = cashPlannerService.getCode(byAgentCode);
        return code;
    }

    @RequestMapping("/pending/order")
    @ResponseBody
    public ApiResponse pendingOrder() {
        List<CeOrdersEntity> list = ordersDao.getTodayPendingOrder("2", "3");
        List<JSONObject> array = Lists.newArrayList();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getMerchantCode().equals("winterloan") || list.get(i).getMerchantCode().equals("jitu")) {
                JSONObject object = new JSONObject();
                object.put("merchantCode", list.get(i).getMerchantCode());
                object.put("agentCode", list.get(i).getAgentCode());
                object.put("orderNo", list.get(i).getOrderNo());
                object.put("status", list.get(i).getStatus());
                object.put("syncStatus", list.get(i).getSyncStatus());
                array.add(object);
            }
        }
        return new ApiResponse(array);
    }

    @RequestMapping("/update/order")
    @ResponseBody
    public ApiResponse updatePendingOrder(String orderNo) {
        ordersDao.updateTodayPendingOrder(4, 6, orderNo);
        return new ApiResponse();
    }


    @RequestMapping("/query/littleorange/order")
    @ResponseBody
    public ApiResponse queryLittleOrange(String orderNo) {
        CeOrdersEntity ordersEntity = ordersDao.getTodayOneByOrderNo(orderNo);
        CeAgentAccountEntity agentAccount = agentAccountDao.getByAgentCode(ordersEntity.getAgentCode());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(ordersEntity.getMerchantCode());
        Any orderInfo = JsonIterator.deserialize(ordersEntity.getOrderInfo());
        if (ordersEntity.getStatus() == 4) {
            return new ApiResponse("Paid");
        }
        Map<String, String> headers = getHeaders(agentAccount);
        String url = merchant.getApiDomain() + "/api/cm_repay_proof/page";
        JSONObject params = new JSONObject();
        JSONObject param = new JSONObject();
        param.put("pageNo", 1);
        param.put("pageSize", 100);
        param.put("cmDunningCaseId", orderInfo.get("id").toString());
        params.put("query", param);
        long st = System.currentTimeMillis();
        String stt = MD5.md5("#cG8wbGttMW5ibG16eDZoYQ#3XELTZUO#" + st);
        String[] cmds = {"curl", "--location", "--request", "POST", url,
                "--header", "Content-Type: application/json",
                "--header", "lang: en-us",
                "--header", "customer: 3XELTZUO",
                "--header", "auth:" + headers.get("auth"),
                "--header", "Referer: " + merchant.getApiDomain() + "/cm-dunning-case-list",
                "--header", "accept: application/json",
                "--header", "accept-encoding: gzip, deflate, br",
                "--header", "accept-language: zh-CN,zh;q=0.9",
                "--header", "content-type: application/json; charset=utf-8",
                "--header", "origin: " + merchant.getApiDomain(),
                "--header", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"",
                "--header", "st:" + st,
                "--header", "stt:" + stt,
                "--header", "sec-ch-ua-mobile: ?0",
                "--header", "sec-ch-ua-platform: \"macOS\"",
                "--header", "sec-fetch-dest: empty",
                "--header", "sec-fetch-mode: cors",
                "--header", "sec-fetch-site: same-origin",
                "--header", "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
                "--data-raw", params.toString()};
        String result = execCurl(cmds);
        LOGGER.info("== 查询LittleOrange补单结果 ==,result:{}", result);
        List<Any> list = JsonIterator.deserialize(result).get("page").get("content").asList();
        if (CollectionUtils.isNotEmpty(list)) {
            String message = list.get(list.size() - 1).get("message").toString();
            return new ApiResponse(message);
        }
        return new ApiResponse("query fail！");
    }


    @RequestMapping("/cashbro/getCaptchakey")
    @ResponseBody
    public String cashBroCaptcha() {
        String captchakey = cashBroService.getCaptchakey();
        return captchakey;
    }

    @RequestMapping("/cashbro/getCaptchakeyBase")
    @ResponseBody
    public String cashBroCaptchaBase() {
        String captchakey = cashBroService.getCaptchakeyBase();
        return captchakey;
    }

    @RequestMapping("/cashbro/login")
    @ResponseBody
    public String cashBroLogin(String agentCode, String code) {
        CeAgentAccountEntity cashbro = agentAccountDao.getByAgentCode(agentCode);
        String result = cashBroService.login(cashbro, code);
        return result;
    }

    @RequestMapping(value = "/prettyloan/captchakey")
    @ResponseBody
    public String prettyloanCode(String agentCode) {
        return prettyLoanService.getCaptchakeyBase(agentCode);
    }

    @RequestMapping("/prettyloan/login")
    @ResponseBody
    public String prettyloanLogin(String agentCode, String code) {
        CeAgentAccountEntity cashbro = agentAccountDao.getByAgentCode(agentCode);
        String result = prettyLoanService.login(cashbro, code);
        return result;
    }


    @RequestMapping("/unpushed/list")
    @ResponseBody
    public ApiResponse unPushedList(@RequestBody UnPushedListRequest request) {
        List<UnPushedListBean> unPushedList = ordersDao.getUnPushedList(request.getMerchantCode());
        return new ApiResponse(unPushedList);
    }

    @RequestMapping("/anomaly/count")
    @ResponseBody
    public ApiResponse anomalyCount() {
        Integer count = ordersDao.anomalyCount();
        LOGGER.info("====,count:{}", count);
        return new ApiResponse(count);
    }

    @RequestMapping("/anomaly/update")
    @ResponseBody
    public ApiResponse updateAnomaly() {
        ordersDao.updateAnomaly();
        return new ApiResponse();
    }

    @RequestMapping("/order/delete")
    @ResponseBody
    public ApiResponse orderDelete() {
        if (DateUtil.getHour() >= 9) {
            return new ApiResponse("11点半之后不允许删除");
        }
        ordersDao.deletedRepaymentOrder();
        return new ApiResponse("删除已还款订单成功");
    }

}
